package cn.handong.tool.annotation.validator;

import cn.handong.tool.annotation.NotAllBlank;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;


public class NotAllBlankValidator implements ConstraintValidator<NotAllBlank, Object> {
	private final static Logger logger = LoggerFactory.getLogger(NotAllBlankValidator.class);
	
	private String[] fields;

	@Override
	public void initialize(NotAllBlank constraintAnnotation) {
		this.fields = constraintAnnotation.fields();
	}

	@Override
	public boolean isValid(Object obj, ConstraintValidatorContext context) {
		String[] valueArray = new String[fields.length];
		try {
			for(int i=0; i < fields.length; i++){
				String name = fields[i];
				name = name.substring(0, 1).toUpperCase() + name.substring(1);
				Method m = obj.getClass().getMethod("get" + name);
				valueArray[i] = (String) m.invoke(obj);
			}
		} catch (Exception e) {
			logger.error("NotAllBlankValidator.isValid:", e);
			return false;
		} finally {
			boolean allBlank = StringUtils.isAllBlank(valueArray);
			if (allBlank) {
				context.disableDefaultConstraintViolation();
				context.buildConstraintViolationWithTemplate("at least one not empty: " + StringUtils.join(fields, " ")).addConstraintViolation();
			}
			return !allBlank;
		}
	}

}
